<template>
  <div class="order-container">
    <div class="table-container">
      <avue-crud
        ref="crudRef"
        :data="data"
        :option="option"
        :page="page"
        v-model:page="page"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchChange"
        @search-reset="searchReset"
        @on-load="onLoad"
        @row-view="onView"
        :loading="loading"
      >
        <!-- 自定义操作按钮 -->
        <template #menu="{ row }">
          <el-button 
            v-if="row.status === ORDER_STATUS.PENDING_DELIVERY"
            type="success" 
            size="small"
            @click="handleUpdateLogistics(row, LOGISTICS_STATUS.SHIPPED)"
          >
            发货
          </el-button>
          <el-button 
            type="primary" 
            size="small"
            @click="handleUpdateAddress(row)"
          >
            更新地址
          </el-button>
          <!-- <el-button 
            v-if="row.status === ORDER_STATUS.PENDING_PAYMENT"
            type="danger" 
            size="small"
            @click="updateStatus(row, ORDER_STATUS.CANCELLED)"
          >
            取消订单
          </el-button> -->
        </template>

        <!-- 自定义状态列 -->
        <template #status="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ ORDER_STATUS_OPTIONS.find(item => item.value === row.status)?.label }}
          </el-tag>
        </template>
      </avue-crud>
    </div>
  </div>

  <!-- 更新地址对话框 -->
  <el-dialog
    v-model="addressDialog.visible"
    title="更新收货地址"
    width="500px"
    destroy-on-close
  >
    <el-form 
      ref="addressFormRef"
      :model="addressDialog.form"
      :rules="addressDialog.rules"
      label-width="80px"
      status-icon
    >
      <el-form-item label="收货人" prop="receiverName">
        <el-input v-model="addressDialog.form.receiverName" placeholder="请输入收货人姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="receiverPhone">
        <el-input v-model="addressDialog.form.receiverPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="receiverAddress">
        <el-input 
          v-model="addressDialog.form.receiverAddress" 
          type="textarea" 
          :rows="3"
          placeholder="请输入详细地址"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addressDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitAddressUpdate" :loading="addressDialog.loading">确认</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getOrderPage, updateLogisticsStatus, updateOrderReceiver, ORDER_STATUS, ORDER_STATUS_OPTIONS, LOGISTICS_STATUS_OPTIONS, LOGISTICS_STATUS } from '@/api/order'

const router = useRouter()

// 地址编辑对话框
const addressDialog = reactive({
  visible: false,
  loading: false,
  orderId: null,
  form: {
    receiverName: '',
    receiverPhone: '',
    receiverAddress: ''
  },
  rules: {
    receiverName: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    receiverPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    receiverAddress: [
      { required: true, message: '请输入收货地址', trigger: 'blur' },
      { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
    ]
  }
})

const addressFormRef = ref(null)

// 表格配置
const option = {
  align: 'center',
  menuAlign: 'center',
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  editBtn: false,
  delBtn: false,
  addBtn: false,
  page: true,
  pageSizes: [10, 20, 30, 50],
  paginationAlign: 'center',
  searchShowBtn: true,
  searchResetBtn: true,
  height: 'auto',
  column: [
    {
      label: '订单编号',
      prop: 'orderNo',
      search: true,
      width: 180,
      overHidden: true
    },
    {
      label: '用户ID',
      prop: 'userId',
      search: true,
      width: 100
    },
    {
      label: '订单金额',
      prop: 'totalAmount',
      type: 'number',
      precision: 2,
      width: 100
    },
    {
      label: '优惠金额',
      prop: 'discountAmount',
      type: 'number',
      precision: 2,
      width: 100
    },
    {
      label: '实付金额',
      prop: 'payAmount',
      type: 'number',
      precision: 2,
      width: 100
    },
    {
      label: '订单状态',
      prop: 'status',
      type: 'select',
      search: true,
      dicData: ORDER_STATUS_OPTIONS,
      width: 100
    },
    {
      label: '物流状态',
      prop: 'logisticsStatus',
      type: 'select',
      dicData: LOGISTICS_STATUS_OPTIONS,
      width: 100
    },
    {
      label: '收货人',
      prop: 'receiverName',
      width: 120
    },
    {
      label: '联系电话',
      prop: 'receiverPhone',
      width: 120
    },
    {
      label: '收货地址',
      prop: 'receiverAddress',
      overHidden: true,
      showOverflowTooltip: true,
      width: 250
    },
    
    {
      label: '支付时间',
      prop: 'payTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      width: 160
    },
    {
      label: '发货时间',
      prop: 'shipTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      width: 160
    },
    
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      width: 160
    },{
      label: '收货时间',
      prop: 'receiveTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      width: 160
    },
    {
      label: '备注',
      prop: 'remark',
      overHidden: true,
      showOverflowTooltip: true,
      width: 150
    },
  ]
}

// 数据对象
const data = ref([])
const loading = ref(false)
const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 加载数据
const onLoad = async (pagination, params) => {
  try {
    loading.value = true
    const queryParams = {
      current: pagination?.currentPage || page.value.currentPage,
      size: pagination?.pageSize || page.value.pageSize,
      ...params
    }
    
    const res = await getOrderPage(queryParams)
    if (res.data.code === 200) {
      const { records, total, current, size } = res.data.data
      data.value = records
      page.value = {
        total,
        currentPage: current,
        pageSize: size
      }
    } else {
      ElMessage.error(res.data.msg || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表出错：', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const onView = (row) => {
  router.push(`/order/detail/${row.id}`)
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case ORDER_STATUS.COMPLETED:
      return 'success'
    case ORDER_STATUS.CANCELLED:
      return 'danger'
    case ORDER_STATUS.PENDING_PAYMENT:
      return 'warning'
    case ORDER_STATUS.PENDING_DELIVERY:
      return 'primary'
    case ORDER_STATUS.PENDING_RECEIVE:
      return 'info'
    case ORDER_STATUS.PENDING_REVIEW:
      return 'warning'
    case ORDER_STATUS.REVIEWED:
      return 'success'
    default:
      return 'default'
  }
}

// 更新订单状态
const updateStatus = async (row, status) => {
  try {
    let confirmMessage = ''
    switch (status) {
      case ORDER_STATUS.PENDING_RECEIVE:
        confirmMessage = '确认发货？'
        break
      // case ORDER_STATUS.CANCELLED:
      //   confirmMessage = '确认取消订单？'
      //   break
      default:
        confirmMessage = '确认更新订单状态？'
    }

    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateLogisticsStatus(row.id, status)
    if (res.data.code === 200) {
      ElMessage.success('操作成功')
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新订单状态出错：', error)
      ElMessage.error('操作失败')
    }
  }
}

// 更新订单物流状态
const handleUpdateLogistics = async (row, logisticsStatus) => {
  try {
    let confirmMessage = ''
    switch (logisticsStatus) {
      case LOGISTICS_STATUS.SHIPPED:
        confirmMessage = '确认发货？'
        break
      case LOGISTICS_STATUS.DELIVERING:
        confirmMessage = '确认开始配送？'
        break
      case LOGISTICS_STATUS.RECEIVED:
        confirmMessage = '确认已签收？'
        break
      default:
        confirmMessage = '确认更新物流状态？'
    }

    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateLogisticsStatus(row.id, logisticsStatus)
    if (res.data.code === 200) {
      ElMessage.success('物流状态更新成功')
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '物流状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新物流状态出错：', error)
      ElMessage.error('物流状态更新失败')
    }
  }
}

// 打开更新地址对话框
const handleUpdateAddress = (row) => {
  addressDialog.orderId = row.id
  addressDialog.form.receiverName = row.receiverName
  addressDialog.form.receiverPhone = row.receiverPhone
  addressDialog.form.receiverAddress = row.receiverAddress
  addressDialog.visible = true
}

// 提交地址更新
const submitAddressUpdate = async () => {
  if (!addressFormRef.value) return
  
  try {
    await addressFormRef.value.validate()
    
    addressDialog.loading = true
    const res = await updateOrderReceiver(addressDialog.orderId, addressDialog.form)
    
    if (res.data.code === 200) {
      ElMessage.success('收货信息更新成功')
      addressDialog.visible = false
      onLoad(page.value) // 刷新列表
    } else {
      ElMessage.error(res.data.msg || '商品已发货，收货信息更新失败')
    }
  } catch (error) {
    console.error('更新收货信息出错：', error)
  } finally {
    addressDialog.loading = false
  }
}

// 分页大小改变
const sizeChange = (val) => {
  page.value.pageSize = val
  onLoad(page.value)
}

// 当前页改变
const currentChange = (val) => {
  page.value.currentPage = val
  onLoad(page.value)
}

// 搜索条件改变
const searchChange = (params, done) => {
  onLoad(page.value, params)
  done()
}

// 重置搜索
const searchReset = () => {
  onLoad(page.value)
}
</script>

<style scoped>
.order-container {
  background-color: var(--white-color);
  padding: var(--main-padding);
  border-radius: var(--border-radius);
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  position: relative;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
}

:deep(.avue-crud__pagination) {
  position: sticky;
  bottom: 0;
  background-color: var(--white-color);
  margin-top: 16px;
  padding: 16px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

:deep(.avue-crud__menu) {
  background-color: var(--white-color);
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
</style> 